package com.qf.core.exception;

import com.qf.core.response.ResponseCode;
import com.qf.core.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @Author: sin
 * @Date: 2025/5/5 14:28
 * @Description: 全局异常
 **/
//@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public ResponseResult<Object> baseExceptionHandler(BaseException e) {
        return ResponseResult.fail(e.getCode(), e.getErrMessage());
    }

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult<Object> handleValidationExceptions(MethodArgumentNotValidException e) {
        String msg  =e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResponseResult.fail(ResponseCode.VALID_ERROR.getCode(), msg == null ? ResponseCode.VALID_ERROR.getDesc() : msg);
    }
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseResult<Object> handleAllExceptions(Throwable ex) {
        return ResponseResult.fail(500, "系统内部错误");
    }


    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
    public ResponseResult<Object> handleMaxSizeException(MaxUploadSizeExceededException ex) {
        return ResponseResult.fail("上传失败，文件大小不能超过限制");
    }

    /**
     * 处理其余异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseResult<Object> otherExceptionHandler(Exception e) {
        return ResponseResult.fail(e.getMessage());
    }
}
